package com.boarsoft.boar.demo.order.biz;

import java.util.List;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.user.entity.PocAccount;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.dao.sharding.bean.DaoSharding;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("orderBiz")
public class PocOrderBizImpl extends SimpleBizImpl implements PocOrderBiz {

	@Override
	@Transactional
	@DaoSharding(policy = "tenant", index = 0)
	// 这里将取PocOrder的hash值来计算数据源，而PocOrder的hash值是tenantId
	public boolean save(PocOrder order) {
		if (dao.save(order) == null) {
			return false;
		}
		return true;
	}

	@Override
	@Transactional
	@DaoSharding(policy = "tenant", index = 0)
	public boolean update(PocOrder order) {
		return dao.update(order);
	}

	@Override
	@Transactional(readOnly = true)
	@DaoSharding(policy = "tenant", index = 0)
	public PocOrder findById(int tenantId, int orderId) {
		// tenantId仅作为分片参数，不用于查询
		return dao.get(PocOrder.class, orderId);
	}

	@Override
	@Transactional
	@DaoSharding(policy = "tenant", index = 0)
	public boolean placeOrder(PocOrder o) {
		// 保存订单
		dao.save(o);
		// 减余额，增加冻结余额
		Query<?> q = dao.createQuery(
				"update PocAccount set availableAmount = availableAmount - ?, lockAmount = lockAmount + ? where userId = ? and tenantId = ? and availableAmount > ?");
		q.setParameter(0, o.getAmount());
		q.setParameter(1, o.getAmount());
		q.setParameter(2, o.getUserId());
		q.setParameter(3, o.getTenantId());
		q.setParameter(4, o.getAmount());
		return q.executeUpdate() == 1;
	}

	@Override
	@Transactional
	@DaoSharding(policy = "tenant", index = 0)
	public void payOrder(int tenantId, PocOrder order, PocAccount account, boolean callType) throws Exception {
		// 设置订单状态
		order.setStatus(PocOrder.STATUS_FINISH);
		order.setModifyTime(Util.getStdmfDateTime());
		dao.update(account);
		dao.update(order);
		//
		if (callType) {
			throw new RuntimeException("测试事务例外");
		}
	}

	@Override
	@Transactional(readOnly = true)
	@DaoSharding(policy = "tenant", index = 0)
	public PagedResult<PocOrder> listByOrderIdAndUserId(int tenantId, int orderId, int userId, String orderBy, int pageNo,
			int pageSize) {

		// 默认查询第一页10条记录
		if (pageNo == 0) {
			pageNo = 1;
		}
		if (pageSize == 0) {
			pageSize = 10;
		}

		StringBuilder sb = new StringBuilder();

		if (orderId != 0) {
			sb.append(" and order_id = " + orderId);
		}
		if (userId != 0) {
			sb.append(" and user_id = " + userId);
		}

		int total = dao.getTotal(PocOrder.class, sb.toString());

		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy);
		}

		List<PocOrder> orders = dao.list(PocOrder.class, sb.toString(), pageNo, pageSize);

		return new PagedResult<PocOrder>(total, orders, pageNo, pageSize);

	}
}
